- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path301.Remove Invalid Parentheses.go
69 lines (65 loc) · 1.26 KB
/
301.Remove Invalid Parentheses.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package leetcode
var (
res []string
mpmap[string]int
nint
lengthint
maxScoreint
strstring
)
funcremoveInvalidParentheses(sstring) []string {
lmoves, rmoves, lcnt, rcnt:=0, 0, 0, 0
for_, v:=ranges {
ifv=='(' {
lmoves++
lcnt++
} elseifv==')' {
iflmoves!=0 {
lmoves--
} else {
rmoves++
}
rcnt++
}
}
n=len(s)
length=n-lmoves-rmoves
res= []string{}
mp=make(map[string]int)
maxScore=min(lcnt, rcnt)
str=s
backtrace(0, "", lmoves, rmoves, 0)
returnres
}
funcbacktrace(iint, curstring, lmovesint, rmovesint, scoreint) {
iflmoves<0||rmoves<0||score<0||score>maxScore {
return
}
iflmoves==0&&rmoves==0 {
iflen(cur) ==length {
if_, ok:=mp[cur]; !ok {
res=append(res, cur)
mp[cur] =1
}
return
}
}
ifi==n {
return
}
ifstr[i] =='(' {
backtrace(i+1, cur+string('('), lmoves, rmoves, score+1)
backtrace(i+1, cur, lmoves-1, rmoves, score)
} elseifstr[i] ==')' {
backtrace(i+1, cur+string(')'), lmoves, rmoves, score-1)
backtrace(i+1, cur, lmoves, rmoves-1, score)
} else {
backtrace(i+1, cur+string(str[i]), lmoves, rmoves, score)
}
}
funcmin(a, bint) int {
ifa<b {
returna
}
returnb
}